/**
 * 
 */
package com.ssl.spring.security.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ssl.spring.security.auth.entity.AuthUser;
import com.ssl.spring.security.auth.entity.SecurityUserDetail;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author
 * @date 2021年4月29日 上午11:17:26
 * @version 1.0
 */
public class TokeUtil {

	private static final String JWT_SECRET = "ssl";

	/**
	 * token有效时长
	 */
	private static final Integer EXPIRES = 24 * 60 * 60 * 1000;

	private static Algorithm hmac256;

	public static final String AUTH_USER = "authUser";

	public static final String PERMISSION_VALUE = "permissionValue";

	static {
		hmac256 = Algorithm.HMAC256(JWT_SECRET);
	}

	public static String createToken(SecurityUserDetail userDetail) {
		Date expireDate = DateUtils.addMilliseconds(new Date(), EXPIRES);
		return JWT.create().withClaim(AUTH_USER, JSONObject.toJSONString(userDetail.getAuthUser()))
				.withClaim(PERMISSION_VALUE,userDetail.getPermissionValueList())
				.withExpiresAt(expireDate).sign(hmac256);
	}


	public static SecurityUserDetail getUserDetail(String token) {
		DecodedJWT decodedJWT = JWT.decode(token);
		String authUserStr = decodedJWT.getClaim(AUTH_USER).asString();

		List<String> permission = decodedJWT.getClaim(PERMISSION_VALUE).asList(String.class);

		AuthUser authUser = JSONObject.parseObject(authUserStr,new TypeReference<AuthUser>(){});

		SecurityUserDetail securityUserDetail = new SecurityUserDetail();
		securityUserDetail.setAuthUser(authUser);
		securityUserDetail.setPermissionValueList(permission);
		return  securityUserDetail;
	}
	
	
	public static void main(String[] args) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

		/*String token = createToken("ssl");
		System.out.println(token);
		String username = getUserInfoFromToken(token);
		System.out.println(username);*/
		AuthUser authUser = new AuthUser();
		authUser.setPassword(encoder.encode("123456"));
		authUser.setNickName("962");
		authUser.setUsername("test");
		authUser.setSalt("fdf");
		SecurityUserDetail userDetail = new SecurityUserDetail();
		userDetail.setAuthUser(authUser);
		userDetail.setPermissionValueList(Arrays.asList("user","admin"));

		String token  = createToken(userDetail);
		System.out.println("token:" + token);
		SecurityUserDetail securityUserDetail = getUserDetail(token);
		System.out.println(securityUserDetail.toString());
	}
}
